#!/bin/sh

GPIO_DEVICE="/dev/mt7621-gpio-control"
LOG_FILE="/var/log/gpio-control.log"

log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" >> "$LOG_FILE"
}

check_device() {
    if [ ! -c "$GPIO_DEVICE" ]; then
        echo "Error: GPIO control device not found: $GPIO_DEVICE"
        log_message "ERROR: Device $GPIO_DEVICE not found"
        return 1
    fi
    return 0
}

gpio_status() {
    if check_device; then
        echo "GPIO22 Status:"
        cat $GPIO_DEVICE
        log_message "INFO: Query GPIO status"
    fi
}

gpio_set_high() {
    if check_device; then
        echo "high" > $GPIO_DEVICE
        echo "GPIO22 set to high level"
        log_message "INFO: Set GPIO22 to high level"
    fi
}

gpio_set_low() {
    if check_device; then
        echo "low" > $GPIO_DEVICE
        echo "GPIO22 set to low level"
        log_message "INFO: Set GPIO22 to low level"
    fi
}

gpio_toggle() {
    if check_device; then
        echo "toggle" > $GPIO_DEVICE
        echo "GPIO22 level toggled"
        log_message "INFO: Toggle GPIO22 level"
    fi
}

case "$1" in
    "status")
        gpio_status
        ;;
    "high")
        gpio_set_high
        ;;
    "low")
        gpio_set_low
        ;;
    "toggle")
        gpio_toggle
        ;;
    "monitor")
        log_message "INFO: Start GPIO monitor mode"
        counter=0
        while [ $counter -lt 30 ]; do
            if [ -c "$GPIO_DEVICE" ]; then
                break
            fi
            sleep 1
            counter=$((counter + 1))
        done
        
        if [ -c "$GPIO_DEVICE" ]; then
            log_message "INFO: GPIO control device ready"
            gpio_set_high
            log_message "INFO: System boot completed, GPIO22 set to high level"
        else
            log_message "ERROR: GPIO control device not ready"
        fi
        ;;
    *)
        echo "Usage: $0 {status|high|low|toggle|monitor}"
        echo "  status  - Show GPIO status"
        echo "  high    - Set GPIO to high level"
        echo("  low     - Set GPIO to low level"
        echo "  toggle  - Toggle GPIO level"
        echo "  monitor - Monitor mode: auto set high after boot"
        exit 1
        ;;
esac

exit 0
